#coding=utf-8
import threading,os
import wx
from pyExcelerator import *
import tree
from fetcher import *

fetchers = [google_cn, ask]#google_com] #yahoo_cn, ask]

def get_suggesttree(query, fetch, parent=None, output_window=None):
    
    root = tree.Node(word=query, parent=parent)
    
    data = fetch(query)
    
    if not data:return root
    
    for d in data:
        print d
        if output_window:
            wx.CallAfter(output_window.LogMessage, d)
        t = get_suggesttree(d, fetch, root, output_window)
        root.add_child(t)
        
    return root

class RList(object):
    def __init__(self):
        self.list = []
    
    def sgtree2list(self, sgtree):
        self.list.append(sgtree.word)
        if not sgtree.children:return
        for child in sgtree.children:
            self.sgtree2list(child)
        
def sgtree2sheet_as_list(sgtree, sheet):
    sheet.write(sgtree.z, 0, sgtree.word)    
    
    if not sgtree.children:return
    
    for child in sgtree.children:
        sgtree2sheet_as_list(child, sheet)
    
def sgtree2sheet_as_tree(sgtree, sheet):
    
    x = sgtree.location.x
    y = sgtree.location.y
    
    sheet.write(y, x+3, sgtree.word)
    
    if not sgtree.children:return
    
    for child in sgtree.children:
        sgtree2sheet_as_tree(child, sheet)

def sgtree2sheet(sgtree, workbook, sheet_name):

    sgtree.mark_number()
    sgtree.mark_number2()
   
    sheet = workbook.add_sheet(sheet_name)
    
    sgtree2sheet_as_list(sgtree, sheet)
    sgtree2sheet_as_tree(sgtree, sheet)

def sgtrees2sheet(sgts, workbook):
    sheet = workbook.add_sheet('all')
    i = 0
    for sgt in sgts:
        rl = RList()
        rl.sgtree2list(sgt)
        for j in range(len(rl.list)):
            sheet.write( j, i, rl.list[j])
        i = i + 1
        
class FetchThread(threading.Thread):
    
    def __init__(self, query, directory, window):
        threading.Thread.__init__(self)
        
        self.query = query
        self.fn = os.path.join(directory, '%s.xls'%query)
        self.window = window
    
    def run(self):
    
        wb = Workbook()
        
        sgts = []
        for fetcher in fetchers:
           
            wx.CallAfter(self.window.LogMessage, fetcher.__name__)
            sgt = get_suggesttree(self.query, fetcher, output_window=self.window)
            sgts.append(sgt)
            sgtree2sheet(sgt, wb, fetcher.__name__)
            
            tree.x = 0
            tree.y = 0
            tree.z = 0
              
        sgtrees2sheet(sgts, wb)
        wb.save(self.fn)
        
        wx.CallAfter(self.window.ThreadFinished, self.query)
         
class MainFrame(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'SuggestFetcher', 
                size=(400, 300))
        panel = wx.Panel(self, -1)
        
        sizer = wx.GridBagSizer(hgap=5, vgap=5)
        
        self.st = wx.StaticText(panel, -1, label=unicode('请输入关键词:', 'u8'), 
                                style=wx.ALIGN_CENTER)
        sizer.Add(self.st, pos=(0, 0))
        
        self.tc = wx.TextCtrl(panel, -1, "harvard", 
                size=(175, -1))
        self.tc.SetInsertionPoint(0)
        sizer.Add(self.tc, pos=(0, 1))
        
        self.bt = wx.Button(panel, -1, "go")
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.bt)
        sizer.Add(self.bt, pos=(0, 2))
        
        self.mt = wx.TextCtrl(panel, -1,
                    size = (350, 200),
                    style=wx.TE_MULTILINE|wx.TE_READONLY)
        sizer.Add(self.mt, pos=(1, 0),span=(3,3) )
        
        panel.SetSizer(sizer)
       
        
    def OnClick(self, event):
        dlg = wx.wx.DirDialog(self, style=0,
                message=unicode("请选择数据文件目录", 'u8')
                )
                
        if dlg.ShowModal() == wx.ID_OK:
            self.directory = dlg.GetPath()
            self.mt.Clear()
            
            wb = Workbook()
            self.query_queue = self.tc.GetValue().split(',')
            
            thread = FetchThread(self.query_queue.pop(0), self.directory, self)
            thread.start()
            
    def LogMessage(self, msg):
        self.mt.AppendText('%s\n'%msg)
        
    def ThreadFinished(self, query):
        
        message_dlg = wx.MessageDialog(None, "%s: %s"%(query, unicode('查询成功!', 'u8')),
                          'A Message Box',
                          wx.OK)
        message_dlg.ShowModal()
        
        if self.query_queue:
            thread = FetchThread(self.query_queue.pop(0), self.directory, self)
            thread.start()
            
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()
